package com.foxconn.ipebg.common.system.controller;

import ipebg.mzk.common.util.Page;
import ipebg.mzk.facade.entity.MsAdminFunction;
import ipebg.mzk.facade.entity.MsAdminRoleAuthority;
import ipebg.mzk.facade.entity.MsFunctionOption;
import ipebg.mzk.facade.system.bean.FunctionBean;
import ipebg.mzk.facade.system.bean.FunctionTreeBean;
import ipebg.mzk.facade.system.service.FunctionService;
import ipebg.mzk.facade.system.service.RoleService;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSON;


/**
 * 對菜單項操作方法
 * @author F3225975
 *
 */
@Controller
@RequestMapping("/function.do")
public class FunctionController{
	 
	 @Resource(name="functionServiceImpl")
	 FunctionService functionServiceImpl;
	 
	 @Resource(name="roleServiceImpl")
	 RoleService roleService;
	
	/**
	 * 加載菜單項頁面方法
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(params = "action=load")
	public String load(HttpServletRequest request, HttpServletResponse response, Model model) {
		
		return "/pages/common/system/function_manage";
	}
				
	/**
	 * 查詢菜單清單
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping(params = "action=list")
	public void functionList(HttpServletRequest request, HttpServletResponse response, Model model) {
		
		int from = Integer.parseInt(request.getParameter("page"));
		int length = Integer.parseInt(request.getParameter("rows")); 
		
		String functionCode = request.getParameter("functionCode");
		String functionName = request.getParameter("functionName");
		MsAdminFunction function = new MsAdminFunction();
		function.setFunctionCode(functionCode);
		function.setFunctionName(functionName);
		
		try {
			
			Page initiontpage = functionServiceImpl.getFunctionList(function,from,length);
			List<MsAdminFunction> functionList= (List<MsAdminFunction>) initiontpage.getResult();
			List<FunctionBean> functionBeanList = functionServiceImpl.toBean(functionList);
			
			Map objMap = new HashMap();
			objMap.put("rows", functionBeanList);
			objMap.put("total", initiontpage.getTotalCount());
			
			response.getWriter().write(JSON.toJSONString(objMap));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 查詢菜單樹
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(params = "action=treelist")
	public void treelist(HttpServletRequest request, HttpServletResponse response, Model model) {
		
		try{
			List<MsAdminFunction> list = functionServiceImpl.getAllList();
			List<FunctionTreeBean> treeList = new ArrayList<FunctionTreeBean>();  
			for(MsAdminFunction entity : list) {
				if(entity.getParentId() == "00" || entity.getParentId().equals("00")) {
					//僅抓取父菜單為00的實體
					List<FunctionTreeBean> children = functionServiceImpl.getFunctionTreeList(entity.getFunctionId());
					FunctionTreeBean bean = new FunctionTreeBean();
					bean.setId(entity.getFunctionId());
					bean.setText(entity.getFunctionName() + " -- " + entity.getFunctionCode());
					bean.setChecked(false);
					bean.setChildren(children);
					treeList.add(bean);
				}
			}
			model.addAttribute("data", treeList);
			response.getWriter().write(JSON.toJSONString(model));
		}catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 根據roleId查詢菜單樹
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(params = "action=treelistbyrole")
	public void treelistbyrole(HttpServletRequest request, HttpServletResponse response, Model model) {
		String roleId = request.getParameter("roleId");
		
		try{
			//獲取該角色下具有的菜單Id
			List<MsAdminRoleAuthority> roleAuthrityList = roleService.findAuthorityByRoleId(roleId);
			List<String> array = new ArrayList<String>();
			for(MsAdminRoleAuthority roleAuth : roleAuthrityList){
				array.add(roleAuth.getFunctionId());
			}
			
			List<MsAdminFunction> list = functionServiceImpl.getAllList();
			List<FunctionTreeBean> treeList = new ArrayList<FunctionTreeBean>();  
			for(MsAdminFunction entity : list) {
				if(entity.getParentId() == "00" || entity.getParentId().equals("00")) {
					//僅抓取父菜單為00的實體
					List<FunctionTreeBean> children = functionServiceImpl.getFunctionTreeListByRoleId(roleId, entity.getFunctionId());
					FunctionTreeBean bean = new FunctionTreeBean();
					bean.setId(entity.getFunctionId());
					bean.setText(entity.getFunctionName() + " -- " + entity.getFunctionCode());
					
					if(array.contains(entity.getFunctionId())){
						bean.setChecked(true);
					}else
						bean.setChecked(false);
					
					bean.setChildren(children);
					treeList.add(bean);
				}
			}
			model.addAttribute("data", treeList);
			response.getWriter().write(JSON.toJSONString(model));
		}catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 新增菜單功能
	 * @param request
	 * @param response
	 * @param model
	 */
	@RequestMapping(params = "action=add")
	public void add(HttpServletRequest request, HttpServletResponse response, Model model) {
		String result = "";
		
		String functionName = request.getParameter("functionName");
		String functionCode = request.getParameter("functionCode");
		String functionUrl = request.getParameter("functionUrl");
		String parentId = request.getParameter("parentId");
		String description = request.getParameter("description");
		
		if(functionServiceImpl.findMsAdminFunctionByCode(functionCode) != null){
			result = "exsit";
		}else{
			MsAdminFunction function = new MsAdminFunction();
			function.setFunctionName(functionName);
			function.setFunctionCode(functionCode);
			function.setFunctionUrl(functionUrl);
			function.setParentId(parentId);
			function.setDescription(description);
			function.setCreatedTime(new Date());
			
			functionServiceImpl.saveOrUpdate(function);
			
			result = "success";
		}
		try {
			response.getWriter().write(result);
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
	
	/**
	 * 編輯菜單功能
	 * @param request
	 * @param response
	 * @param model
	 */
	@RequestMapping(params = "action=edit")
	public void edit(HttpServletRequest request, HttpServletResponse response, Model model) {
		String result = "";
		String functionId = request.getParameter("functionId");
		String functionName = request.getParameter("functionName");
		String functionCode = request.getParameter("functionCode");
		String functionUrl = request.getParameter("functionUrl");
		String parentId = request.getParameter("parentId");
		String description = request.getParameter("description");
		
		MsAdminFunction function = functionServiceImpl.findMsAdminFunctionById(functionId);
		MsAdminFunction validationFunction = functionServiceImpl.findMsAdminFunctionByCode(functionCode);
		
		if(validationFunction != null && !(validationFunction.getFunctionId() == functionId || validationFunction.getFunctionId().equals(functionId))){
			result = "exsit";
		}else{
			function.setFunctionName(functionName);
			function.setFunctionCode(functionCode);
			function.setFunctionUrl(functionUrl);
			function.setParentId(parentId);
			function.setDescription(description);
			function.setEditTime(new Date());
			
			functionServiceImpl.saveOrUpdate(function);
			
			result = "success";
		}
		
		try {
			response.getWriter().write(result);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 刪除角色功能
	 * @param request
	 * @param response
	 * @param model
	 */
	@RequestMapping(params = "action=delete")
	public void delete(HttpServletRequest request, HttpServletResponse response, Model model) {
		String functionId = request.getParameter("functionId");
		
		try {
			List<MsAdminRoleAuthority> roleAuthorityBeanList = functionServiceImpl.findAuthorityByFunctionId(functionId);
			List<MsFunctionOption> optionList = functionServiceImpl.findOptionByFunctionId(functionId);
			if(optionList.size() > 0 || roleAuthorityBeanList.size() > 0 ){
				response.getWriter().write("used");
			}else{
				if(functionServiceImpl.deleteFunction(functionId)){
					response.getWriter().write("success");
				}else{
					response.getWriter().write("error");
				}
			}						
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
}
